package com.sx.pipeline.ui.map

import android.app.Application
import android.text.TextUtils
import com.amap.api.services.core.PoiItem
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ToastUtils
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.bus.RxBus
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.app.event.BusEvent
import com.sx.pipeline.app.event.EventTypes
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.repos.http.req.DistrictBorderDTO
import com.sx.pipeline.repos.http.res.Ipage
import com.sx.pipeline.repos.http.res.TerritoryVO
import com.sx.pipeline.repos.local.db.table.PipeFileBeanDO
import com.sx.pipeline.ui.map.entity.DrawLatLng
import com.sx.pipeline.utils.kml.FileParseBean
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers

/**
 * @Author: YY
 * @Date: 2022/5/6
 * @Description: TODO
 */
class MapVM(app: Application) : CYBaseViewModel(app) {

    override fun registerRxBus() {
        addSubscribe(RxBus.getDefault().toObservable(BusEvent::class.java)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                when (it.type) {
                    EventTypes.SELECT_SITE.code -> {
                        val poiItem: PoiItem = it.data as PoiItem
                        Logs.d("选择的地点：${poiItem.cityName} === ${poiItem.snippet} === ${poiItem.distance} ")
                        Logs.d("选择的地点：${poiItem.latLonPoint.latitude} === ${poiItem.latLonPoint.longitude}")
//
//                        val gps = GPSUtil.gcj02_To_Gps84(poiItem.latLonPoint.latitude, poiItem.latLonPoint.longitude)
//                        Logs.d("选择的地点：${gps[0]}")
//                        Logs.d("选择的地点：${ GPSUtil.gps84_To_Gcj02(gps[0], gps[1])[0].toString()}")

                    }
                }
            }
        )
    }

    /**
     * 添加负责区域
     */

    val drawTerritoryEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    fun addTerritory(fileName: String, drawLatLng: MutableList<DrawLatLng>) {
        Logs.d("addTerritory $fileName")
        if (TextUtils.isEmpty(fileName)) {
            ToastUtils.showShort("请输入绘制名称")
            return
        }
        if (drawLatLng.isEmpty()) {
            ToastUtils.showShort("请绘制相关图形")
            return
        }
        val nodesBeanList: MutableList<FileParseBean.NodesBean> = mutableListOf()
        val fileParseBean = FileParseBean()
        fileParseBean.name = fileName
        fileParseBean.type = 0
        drawLatLng.forEach {
            val nodesBean: FileParseBean.NodesBean =
                FileParseBean.NodesBean(it.latLng.longitude, it.latLng.latitude)
            nodesBeanList.add(nodesBean)
        }
        fileParseBean.nodesBeans = nodesBeanList

        addSubscribe(mModel.addTerritory(fileParseBean)
            .compose(RxThreadHelper.rxSchedulerHelper())
            .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                (this, true) {
                override fun onResult(result: Any) {
                    ToastUtils.showShort("添加成功")
                    drawTerritoryEvent.call()
                }

                override fun onFailed(code: Int, msg: String?) {
                    super.onFailed(code, msg)
                    ToastUtils.showShort(msg)
                }
            })
        )
    }

    /**
     * 获取区域列表
     */
    val territoryListEvent: SingleLiveEvent<Ipage<TerritoryVO>> = SingleLiveEvent()

    fun getTerritoryList() {
        addSubscribe(mModel.getTerritoryList(-1, isPage = false, page = 0)
            .compose(RxThreadHelper.rxSchedulerHelper())
            .subscribeWith(object : CommonObserver<Ipage<TerritoryVO>, BaseViewModel<*>>
                (this, true) {

                override fun onResult(result: Ipage<TerritoryVO>) {
                    Logs.d("getTerritoryList ${result.records.size}")
                    territoryListEvent.postValue(result)
                }

                override fun onFailed(code: Int, msg: String?) {
                    super.onFailed(code, msg)

                }
            })
        )
    }


    val territoryListEven2t: SingleLiveEvent<List<PipeFileBeanDO>> = SingleLiveEvent()
    fun getLocalMapList() {
        addSubscribe(
            Single.merge(mModel.getFileBeanAll(0), mModel.getFileBeanAll(1))
                .collectInto(ArrayList<PipeFileBeanDO>(),{list,valueList->valueList.forEach { list.add(it) }})
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    territoryListEven2t.postValue(it)
                })
        )
    }


    /**
     * 获取行政区域
     */
    val districtBorderListEvent: SingleLiveEvent<List<DistrictBorderDTO>> = SingleLiveEvent()

    fun getDistrictBorderList() {
        addSubscribe(mModel.getDistrictBorderList(1, limit = 9999)
            .compose(RxThreadHelper.rxSchedulerHelper())
            .subscribeWith(object : CommonObserver<Ipage<DistrictBorderDTO>, BaseViewModel<*>>
                (this, true) {

                override fun onResult(result: Ipage<DistrictBorderDTO>) {
                    Logs.d("getTerritoryList ${result.records.size}")
                    districtBorderListEvent.postValue(result.records)

                }

                override fun onFailed(code: Int, msg: String?) {
                    super.onFailed(code, msg)
                }
            })
        )
    }

}